/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.parameter_constraints;

import org.jmock.core.Constraint;

import picounit.util.Equal;
import picounit.verify.constraint.EqualUtil;

public class StringMatching implements Constraint, Equal<StringMatching> {
	private final String pattern;

	public StringMatching(String pattern) {
		this.pattern = pattern;
	}
	
	public boolean hasPattern(String pattern) {
		return this.pattern.equals(pattern);
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Constraint methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	public boolean eval(Object object) {
		return object instanceof String && matchesPattern((String) object);
	}

	private boolean matchesPattern(String string) {
		return string.matches(pattern);
	}

	public StringBuffer describeTo(StringBuffer buffer) {
        return buffer.append("a string matching \"")
        	.append(pattern)
        	.append("\"");
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////
	// Equal methods
	///////////////////////////////////////////////////////////////////////////////////////////////
	
	public boolean equalTo(StringMatching stringMatching) {
		return stringMatching.hasPattern(pattern);
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////
	// Object methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public boolean equals(Object object) {
		return EqualUtil.isEqual(this, object);
	}

	@Override
	public int hashCode() {
		return pattern.hashCode();
	}
}
